<script setup>
import { usePDF, VuePDF } from '@tato30/vue-pdf'
import { debounce } from 'lodash-es'
import { ref } from 'vue'

const props = defineProps({
  url: String,
})
const dialogVisible = ref(false)
const page = ref(1)
const pdfpage = ref(1)
const scale = ref(1)

const loading = ref(true)
const progress = ref(0)
function onProgress({ loaded, total }) {
  console.log(`${loaded / total * 100}% Loaded`)
  if (loaded / total >= 1) {
    loading.value = false
  }
  progress.value = Number.parseInt(loaded / total * 100)
  if (progress.value > 100) {
    progress.value = 100
  }
}

function onError(reason) {
  console.error(`PDF加载失败: ${reason}`)
}

const { pdf, pages } = usePDF(props.url, {
  onProgress,
  onError,
})

function viewer() {
  dialogVisible.value = true
}

function pageTo() {
  page.value = Number(pdfpage.value)
  pdfpage.value = null
}

const handleScroll = debounce((e) => {
  e.preventDefault()
  if (e.deltaY < 0) {
    scale.value += 0.1
  }
  else {
    scale.value = Math.max(0.1, scale.value - 0.1)
  }
}, 100)
</script>

<template>
  <div>
    <div class="mx-auto w-60% flex items-center justify-between">
      <button :disabled="page <= 1" class="btn" @click="page = page > 1 ? page - 1 : page">
        上一页
      </button>
      <span>{{ page }} / {{ pages }}</span>
      <button :disabled="page >= pages" class="btn" @click="page = page < pages ? page + 1 : page">
        下一页
      </button>
      <div>
        到第
        <el-input v-model.number="pdfpage" style="width: 60px;" :max="pages" />
        页
      </div>
      <button class="btn" :disabled="!pdfpage" @click="pageTo()">
        确定
      </button>
    </div>
    <div class="relative m-20px min-h-50vh flex justify-center">
      <div v-if="loading" class="absolute left-0 top-0 z-2 h-full w-full flex flex-col items-center justify-center justify-center bg-white/50">
        <span class="my-10px">PDF文件加载中,请稍候...</span>
        <el-progress :text-inside="true" :percentage="progress" class="w-50%" :stroke-width="15" striped striped-flow color="#3DB68A" />
      </div>
      <VuePDF :pdf="pdf" :page="page" style="display: flex" class="justify-center" @click="viewer(pdf)" />
    </div>
    <el-dialog v-model="dialogVisible" width="90%" title="" append-to-body>
      <VuePDF :pdf="pdf" :scale="scale" :page="page" style="display: flex" class="justify-center" @wheel.prevent="handleScroll" />
    </el-dialog>
  </div>
</template>
